import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import MenuBar from './MenuBar';
import MenuManager from './MenuManager';
import UserManager from './UserManager';
import ContentManager from './ContentManager';
import './Dashboard.css';

const pathToMenu = [
  { path: '/dashboard', label: '仪表盘' },
  { path: '/work', label: '工作台' },
  { path: '/analysis', label: '分析页' },
  { path: '/ecommerce', label: '电子商务' },
  { path: '/system/users', label: '用户管理' },
  { path: '/system/menus', label: '菜单管理' },
  { path: '/content/manage', label: '内容管理' },
  { path: '/system', label: '系统管理' }
];

const Dashboard = () => {
  const [user, setUser] = useState(null);
  const location = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 获取用户信息
    const token = localStorage.getItem('token');
    if (token) {
      fetch('/api/user', {
        headers: { 'Authorization': `Bearer ${token}` }
      })
        .then(res => res.json())
        .then(data => {
          setUser(data.user);
          setLoading(false);
        })
        .catch(() => setLoading(false));
    } else {
      setLoading(false);
    }
  }, []);

  const onLogout = async () => {
    await fetch('/api/logout', { method: 'POST', headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } });
    localStorage.removeItem('token');
    window.location.href = '/login';
  };

  // 菜单栏高亮与跳转
  const handleMenuSelect = (menu) => {
    if (menu.key && menu.key !== location.pathname) {
      navigate(menu.key);
    }
  };

  // 根据路由渲染内容
  const getContent = (pathname) => {
    switch (pathname) {
      case '/dashboard':
        return <div style={{fontSize:'1.5rem'}}>欢迎来到仪表盘！</div>;
      case '/work':
        return <div style={{fontSize:'1.5rem'}}>这里是工作台内容。</div>;
      case '/analysis':
        return <div style={{fontSize:'1.5rem'}}>分析页内容展示。</div>;
      case '/ecommerce':
        return <div style={{fontSize:'1.5rem'}}>电子商务相关内容。</div>;
      case '/system/users':
        return <UserManager onLogout={onLogout} />;
      case '/system/menus':
        return <MenuManager />;
      case '/content/manage':
        return <ContentManager />;
      case '/system':
        return <div style={{fontSize:'1.5rem'}}>系统管理首页。</div>;
      default:
        return (
          <div className="dashboard-modern-container">
            <div className="dashboard-modern-header">
              <div className="dashboard-modern-avatar">
                {user?.username?.charAt(0).toUpperCase()}
              </div>
              <div className="dashboard-modern-welcome">
                <h1>欢迎回来，<span className="highlight">{user?.username}</span>！</h1>
                <p className="dashboard-modern-email">{user?.email}</p>
              </div>
              <button onClick={onLogout} className="dashboard-modern-logout">登出</button>
            </div>
            <div className="dashboard-modern-stats">
              <div className="dashboard-modern-stat-card user-id">
                <div className="stat-icon-large">👤</div>
                <div>
                  <div className="stat-label">用户ID</div>
                  <div className="stat-value">{user?.id}</div>
                </div>
              </div>
              <div className="dashboard-modern-stat-card email">
                <div className="stat-icon-large">📧</div>
                <div>
                  <div className="stat-label">邮箱</div>
                  <div className="stat-value">{user?.email}</div>
                </div>
              </div>
              <div className="dashboard-modern-stat-card auth">
                <div className="stat-icon-large">🔐</div>
                <div>
                  <div className="stat-label">认证状态</div>
                  <div className="stat-value success">已认证</div>
                </div>
              </div>
              <div className="dashboard-modern-stat-card time">
                <div className="stat-icon-large">⏰</div>
                <div>
                  <div className="stat-label">登录时间</div>
                  <div className="stat-value">{new Date().toLocaleString('zh-CN')}</div>
                </div>
              </div>
            </div>
            <div className="dashboard-modern-section">
              <h2>系统功能</h2>
              <div className="dashboard-modern-features">
                <div className="feature-group">
                  <div className="feature-item"><span className="feature-icon">✅</span> 用户认证与授权</div>
                  <div className="feature-item"><span className="feature-icon">✅</span> JWT令牌管理</div>
                  <div className="feature-item"><span className="feature-icon">✅</span> 密码加密存储</div>
                </div>
                <div className="feature-group">
                  <div className="feature-item"><span className="feature-icon">✅</span> 响应式设计</div>
                  <div className="feature-item"><span className="feature-icon">✅</span> 现代化UI界面</div>
                </div>
              </div>
            </div>
          </div>
        );
    }
  };

  if (loading) {
    return <div style={{textAlign:'center',marginTop:80}}>加载中...</div>;
  }

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: '#f5f7fa' }}>
      <MenuBar onSelect={handleMenuSelect} selectedKey={location.pathname} />
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '32px 0' }}>
        <div style={{ width: '100%', maxWidth: 1200 }}>
          {getContent(location.pathname)}
        </div>
      </div>
    </div>
  );
};

export default Dashboard; 